package com.jie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jie.dto.OperationLogDTO;
import com.jie.dto.UserInfoFriendDTO;
import com.jie.enums.BizCodeEnum;
import com.jie.exception.BusinessException;
import com.jie.mapper.UserAdminMapper;
import com.jie.mapper.UserInfoMapper;
import com.jie.pojo.FriendIm;
import com.jie.mapper.FriendImMapper;
import com.jie.pojo.UserAdmin;
import com.jie.pojo.UserInfo;
import com.jie.service.FriendImService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.util.BeanCopyUtils;
import com.jie.dto.FriendDTO;
import com.jie.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  好友服务实现类
 * </p>
 *
 * @author xiaojie
 * @since 2023-11-01
 */
@Slf4j
@Service
public class FriendImServiceImpl extends ServiceImpl<FriendImMapper, FriendIm> implements FriendImService {

    @Autowired
    private UserAdminMapper userAdminMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public List<FriendDTO> findFriendByUserId(String username) {
        UserAdmin userAdmin = userAdminMapper.selectOne(new LambdaQueryWrapper<UserAdmin>().eq(UserAdmin::getUsername, username));
        //根据id寻找到全部好友信息
        List<FriendIm> friendIms = this.baseMapper.selectList(new LambdaQueryWrapper<FriendIm>()
                .eq(FriendIm::getInitiatorId, userAdmin.getUserInfoId())
                .eq(FriendIm::getIsDelete,BizCodeEnum.TRUE.getCode()));
              //映射为DTO类型
        List<FriendDTO> friends = BeanCopyUtils.copyList(friendIms, FriendDTO.class);
        return friends;
    }

    @Transactional
    @Override
    public void addFriend(Long friendId) {
        long userId= UserUtils.getLoginUser().getUserInfoId();
        if(userId == friendId){
            throw new BusinessException(BizCodeEnum.PROGRAM_ERROR.getCode(),BizCodeEnum.PROGRAM_ERROR.getMessage());
        }

        //TODO 发送好友申请请求 判断是否同意好友

        // 互相绑定好友关系
        FriendImServiceImpl proxy = (FriendImServiceImpl) AopContext.currentProxy();
        proxy.bindFriend(userId,friendId);
        proxy.bindFriend(friendId,userId);
        log.info("添加好友，用户id:{},好友id:{}",userId,friendId);
    }

    /**
     * 根据id查询好友详细信息
     * @param friendId
     * @return
     */
    @Override
    public UserInfoFriendDTO getFriendInfo(Long friendId) {
        UserInfo userInfo = userInfoMapper.selectById(friendId);
        UserInfoFriendDTO userInfoFriendDTO = UserInfoFriendDTO.builder()
                .nickname(userInfo.getNickname())
                .phone(userInfo.getPhone())
                .email(userInfo.getEmail())
                .avatar(userInfo.getAvatar())
                .build();
        return userInfoFriendDTO;
    }
    @Transactional
    @Override
    public String removeFriendId(Long friendId) {
        FriendIm friendIm = this.baseMapper.selectOne(new LambdaQueryWrapper<FriendIm>()
                .eq(FriendIm::getReceiverId, friendId)
                .eq(FriendIm::getInitiatorId, UserUtils.getLoginUser().getUserInfoId()));
        int delete = this.baseMapper.deleteById(friendIm);
        if (delete>0){
            return "删除好友"+friendIm.getNickName()+"成功";
        }
        return "删除失败 请联系管理员";
    }

    /**
     * 绑定好友关系
     * @param userId
     * @param friendId
     */
    public void bindFriend(Long userId, Long friendId) {
       //判断是否已经是好友了
        if (this.count(new LambdaQueryWrapper<FriendIm>()
                .eq(FriendIm::getInitiatorId,userId)
                .eq(FriendIm::getReceiverId,friendId))==0){
            //根据friendId获取好友名称与头像信息
            UserInfo friendInfo = userInfoMapper.selectById(friendId);
            FriendIm friendIm = FriendIm.builder()
                    .initiatorId(userId)
                    .receiverId(friendId)
                    .avatar(friendInfo.getAvatar())
                    .nickName(friendInfo.getNickname())
                    .build();
            //添加数据库
            this.baseMapper.insert(friendIm);
        }
    }
}
